package com.campos.collection;

import android.media.Image;
import android.os.Handler;
import android.os.HandlerThread;

import com.campos.common.Config;
import com.campos.common.Util;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;

public class ImageSaver {
    private HandlerThread mBackgroundThread;
    private Handler mBackgroundHandler;

    private static class ImageWriter implements Runnable {

        /**
         * The JPEG image
         */
        private final Image mImage;

        ImageWriter(Image image) {
            mImage = image;
        }

        @Override
        public void run() {
            ByteBuffer buffer = mImage.getPlanes()[0].getBuffer();
            byte[] bytes = new byte[buffer.remaining()];
            buffer.get(bytes);
            FileOutputStream output = null;
            try {
                String imgfile = Config.instance().getCurrentImageFilePath();
                Util.CreateFileParentDir(imgfile);
                File imgf = new File(imgfile);
                output = new FileOutputStream(imgf);
                output.write(bytes);
                Config.instance().makeNextImage();
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                mImage.close();
                if (null != output) {
                    try {
                        output.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }

    }

    public void init(){
        mBackgroundThread = new HandlerThread("CameraBackground");
        mBackgroundThread.start();
        mBackgroundHandler = new Handler(mBackgroundThread.getLooper());
    }
    private static ImageSaver gsaver = null;
    public void save(Image img){
        mBackgroundHandler.post(new ImageWriter(img));
    }
    public static void saveImage(Image img){
        if(gsaver == null){
            gsaver = new ImageSaver();
            gsaver.init();
        }
        gsaver.save(img);
    }
}
